package com.uinnova.product.eam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.exception.ServiceException;
import com.binary.jdbc.Page;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.uinnova.product.eam.comm.model.*;
import com.uinnova.product.eam.comm.model.es.*;
import com.uinnova.product.eam.config.Env;
import com.uinnova.product.eam.model.*;
import com.uinnova.product.eam.model.vo.AppNameVo;
import com.uinnova.product.eam.service.*;
import com.uinnova.product.vmdb.comm.i18n.MessageUtil;
import com.uinnova.product.vmdb.comm.i18n.VerifyType;
import com.uinnova.product.vmdb.comm.model.ci.CCcCi;
import com.uinnova.product.vmdb.comm.model.ci.CCcCiClass;
import com.uinnova.product.vmdb.comm.model.ci.CcCi;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiClassInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CiGroupPage;
import com.uinnova.project.base.diagram.comm.diagram.EamDiagramQuery;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uinnova.project.base.diagram.comm.model.ESSimpleDiagramDTO;
import com.uinnova.project.db.eam.ESDiagramDao;
import com.uino.api.client.cmdb.ICIClassApiSvc;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.cmdb.base.ESCIInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.query.ESCISearchBean;
import com.uino.bean.permission.base.SysRole;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.UserInfo;
import com.uino.bean.permission.query.CSysUser;
import com.uino.service.util.FileUtil;
import com.uino.util.rsm.RsmUtils;
import com.uino.util.sys.SysUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Deprecated
@Service
public class IamsDiagramSvcImpl implements IEamDiagramSvc {

    private static final Logger log = LoggerFactory.getLogger(IamsDiagramSvcImpl.class);

    @Value("${http.resource.space}")
    private String httpResouceUrl;

    @Autowired
    private VcDiagramSvc diagramSvc;


    @Value("${local.resource.space}")
    private String localPath;

    @Resource
    private ICIClassApiSvc iciClassApiSvc;

    @Autowired
    private IamsCIDesignSvc iamsCiDesignSvc;

    @Autowired
    ICISwitchSvc ciSwitchSvc;

    @Autowired
    private IUserApiSvc userApiSvc;

    @Autowired
    private IFolderPermissionManagerService folderPermissionManagerService;

    @Autowired
    private RsmUtils rsmUtils;

    @Override
    public List<VcDiagram> queryDiagramList(DiagramQueryBean cdt, String orders) {
        if (cdt == null) {
            cdt = new DiagramQueryBean();
        }
        if (0 != SysUtil.getCurrentUserInfo().getId() && (cdt.getByUser() != null && cdt.getByUser())) {
            cdt.setUserId(SysUtil.getCurrentUserInfo().getId());
        }
        List<VcDiagram> vcDiagrams = diagramSvc.queryDiagramList(SysUtil.getCurrentUserInfo().getDomainId(), cdt, orders);
        if (!CollectionUtils.isEmpty(vcDiagrams)) {
            vcDiagrams.forEach(diagram -> {
                // 缩略图
                String icon1 = diagram.getIcon1();
                if (icon1 != null && !icon1.startsWith(httpResouceUrl)) {
                    icon1 = httpResouceUrl + icon1;
                    diagram.setIcon1(icon1);
                }
            });
        }
        return vcDiagrams;
    }

    @Override
    public Page<VcDiagram> queryDiagramListPage(DiagramQueryBean cdt, String orders) {
        if (cdt == null) {
            cdt = new DiagramQueryBean();
        }
        if (0 != SysUtil.getCurrentUserInfo().getId() && (cdt.getByUser() != null && cdt.getByUser())) {
            cdt.setUserId(SysUtil.getCurrentUserInfo().getId());
        }
        Page<VcDiagram> vcDiagramPage = diagramSvc.queryDiagramPage(SysUtil.getCurrentUserInfo().getDomainId(), cdt.getPageNum()
                , cdt.getPageSize(), cdt, orders);
        List<VcDiagram> vcDiagrams = vcDiagramPage.getData();
        if (!CollectionUtils.isEmpty(vcDiagramPage.getData())) {
            vcDiagrams.forEach(diagram -> {
                // 缩略图
                String icon1 = diagram.getIcon1();
                if (icon1 != null && !icon1.startsWith(httpResouceUrl)) {
                    icon1 = httpResouceUrl + icon1;
                    diagram.setIcon1(icon1);
                }
            });
        }
        return vcDiagramPage;
    }

    @Override
    public Long copyDiagramById(String newName, Long newDirId, Long diagramId){
        SysUser loginUser = SysUtil.getCurrentUserInfo();
        Long domainId = loginUser.getDomainId();
        VcDiagramInfo diagramInfo = diagramSvc.queryDiagramInfoById(domainId, diagramId, new DiagramQ[] {});
        if (diagramInfo == null) {
            MessageUtil.throwVerify(VerifyType.NOT_EXIST, "diagram", null);
        }

        trimDiagram(diagramInfo);

        VcDiagram diagram = diagramInfo.getDiagram();
        // 视图具体内容
        String json = diagramInfo.getJson();
        // 缩略图base64编码
        String thumbnail = diagramInfo.getThumbnail();
        // 视图json信息存储地址
        String jsonPath = "";
        String iconPath = "";
/*        if (!StringUtils.isEmpty(jsonPath)) {
            jsonPath = jsonPath.replaceFirst(httpResouceUrl, "");
        }

        if (!StringUtils.isEmpty(iconPath)) {
            iconPath = iconPath.replaceFirst(httpResouceUrl, "");
        }*/
        diagram.setId(null);
        // 保存视图信息实体文件
        if (!StringUtils.isEmpty(json)) {
            try {
                jsonPath = this.saveOrUpdateResource(UUID.randomUUID().toString() + ".json", json.getBytes(), true);
            } catch (IOException e) {
                log.error("保存视图信息实体文件异常", e);
            }
        }
        if (!StringUtils.isEmpty(thumbnail)) {
            try {
                iconPath = this.saveOrUpdatePng(UUID.randomUUID().toString() + ".png",
                        thumbnail, true);
            } catch (IOException e) {
                log.error("保存png文件异常", e);
            }
        }

        if (!StringUtils.isEmpty(iconPath)) {
            diagram.setIcon1(iconPath);
        }
        if (!StringUtils.isEmpty(jsonPath)) {
            diagram.setDiagramJson(jsonPath);
        }
        diagram.setDiagramBgImg(subRsmSlaveRoot(diagram.getDiagramBgImg()));

        if (newName != null) {
            diagram.setName(newName);
        }
        if (newDirId != null) {
            diagram.setDirId(newDirId);
        }
        diagram.setUserId(loginUser.getId());
        diagram.setIsOpen(0);
        diagram.setIcon1(iconPath);

        List<VcDiagramEle> diagramEles = diagramInfo.getDiagramEles();
        if (diagramEles != null) {
            for (VcDiagramEle vcDiagramEle : diagramEles) {
                vcDiagramEle.setId(null);
                vcDiagramEle.setDiagramId(null);
            }
        }
        if (diagram.getDiagramType() == 2) {
            List<DcCombDiagram> combDiagrams = diagramInfo.getCombDiagrams();
            if (!BinaryUtils.isEmpty(combDiagrams)) {
                for (DcCombDiagram combDiagram : combDiagrams) {
                    combDiagram.setId(null);
                }
            }

        }
        return diagramSvc.saveOrUpdateDiagram(domainId, diagramInfo);
    }

    @Override
    public Integer updateDiagramNameById(String newName, Long newDirId, Long diagramId) {
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        MessageUtil.checkEmpty(diagramId, "id");
        return diagramSvc.updateDiagramNameAndDirIdById(domainId, newName, newDirId, diagramId);
    }

    @Override
    public List findCiSysList(Integer type, String name) {
        MessageUtil.checkEmpty(type, "type");
        String appName = null;
        if (type == 1) {
            appName = Env.APP_SUBSYSTEM.getClassName();
        } else if (type == 2) {
            appName = Env.APP.getClassName();
        } else {
            throw new ServiceException("参数异常!");
        }
        if (StringUtils.isEmpty(appName)) {
            throw new ServiceException("系统名称不能为空!");
        }
        CCcCiClass cCcCiClass = new CCcCiClass();
        cCcCiClass.setClassNameEqual(appName);
        List<CcCiClassInfo> ccCiClassList = iciClassApiSvc.queryClassByCdt(cCcCiClass);
        Long classId = ccCiClassList.get(0).getCiClass().getId();
        ESCISearchBean bean = new ESCISearchBean();
        CCcCi cdt = new CCcCi();
        cdt.setClassId(classId);
        bean.setCdt(cdt);
        Long count = iamsCiDesignSvc.countByQuery(bean);
        bean.setPageSize(count.intValue());
        CiGroupPage ciGroupPage = iamsCiDesignSvc.queryPageBySearchBean(bean, false);
        List<CcCiInfo> data = ciGroupPage.getData();
        List<AppNameVo> appList = new ArrayList<>();
        if (CollectionUtils.isEmpty(data)) {
            return appList;
        }
        data.forEach(ccCiInfo -> {
            CcCi ci = ccCiInfo.getCi();
            if (ci != null) {
                AppNameVo appNameVo = new AppNameVo();
                appNameVo.setId(ci.getId());
                String ciPrimaryKey = ci.getCiPrimaryKey();
                List<String> strList = (List)JSON.parseArray(ciPrimaryKey);
                String content = strList.get(1);
                appNameVo.setAppName(content);
                if (!StringUtils.isEmpty(name)) {
                    if (content.contains(name)) {
                        appList.add(appNameVo);
                    }
                } else {
                    appList.add(appNameVo);
                }
            }
        });
        return appList;
    }

    @Override
    public Long insertCiSysDesign(Integer type, Long ciId) {
        MessageUtil.checkEmpty(type, "type");
        MessageUtil.checkEmpty(ciId, "id");
        if (type != 1 && type != 2) {
            throw new ServiceException("参数异常!");
        }
        CcCiInfo ciInfo = iamsCiDesignSvc.getCiInfoById(ciId);
        if (ciInfo != null) {
            SysUser loginUser = SysUtil.getCurrentUserInfo();
            Long dirId = null;
            if (type == 1) {
                // 新增数据库代码
                VcDiagramDir record = new VcDiagramDir();
                record.setDirName(ciInfo.getAttrs().get("子系统名称"));
                record.setParentId(1L);
                record.setUserId(loginUser.getId());
                record.setDomainId(1L);
                record.setDirType(11);
                record.setSubjectId(0L);
                record.setDataStatus(1);
                record.setEsSysId(ciInfo.getCi().getCiCode());
                record.setDirInit(0);
                record.setSysDir(1);

                // 系统分类
                record.setSysType(ciInfo.getAttrs().get("子系统分类"));
                dirId = diagramSvc.saveOrUpdateDiagramDir(1L, record);
            }
            return dirId;
        }
        return 0L;
    }

    @Override
    public List<VcDiagramDir> querypublicDesignDir() {
        // 获取登录人的信息
        SysUser loginUser = SysUtil.getCurrentUserInfo();
        Long userId = loginUser.getId();
        Long domainId = loginUser.getDomainId();

        // 查询子系统
        CVcDiagramDir cdt = new CVcDiagramDir();
        cdt.setDomainId(domainId);
        cdt.setDataStatus(1);
        cdt.setDirType(11);
        cdt.setDirInit(0);
        /*if (!StringUtils.isEmpty(dirName)) {
            // 模糊搜索
            dirName = "%" + dirName + "%";
            cdt.setDirName(dirName);
        }*/
        return diagramSvc.queryDiagramDirList(domainId, cdt, "MODIFY_TIME DESC, ORDER_NO");
    }

    @Override
    public Long insertCiSysDir(int type, Long ciId) {
        MessageUtil.checkEmpty(type, "type");
        MessageUtil.checkEmpty(ciId, "id");
        if (type != 1 && type != 2) {
            throw new ServiceException("参数异常!");
        }
        CcCiInfo ciInfo = iamsCiDesignSvc.getCiInfoById(ciId);
        if (ciInfo != null) {
            SysUser loginUser = SysUtil.getCurrentUserInfo();
            Long dirId = null;
            if (type == 1) {
                // 新增数据库代码
                VcDiagramDir record = new VcDiagramDir();
                record.setDirName(ciInfo.getAttrs().get("子系统名称"));
                record.setParentId(1L);
                //record.setUserId(loginUser.getId());
                record.setDomainId(1L);
                record.setDirType(11);
                record.setSubjectId(0L);
                record.setDataStatus(1);
                record.setEsSysId(ciInfo.getCi().getCiCode());
                record.setDirInit(0);
                // 系统分类
                record.setSysType(ciInfo.getAttrs().get("子系统分类"));
                dirId = diagramSvc.saveOrUpdateDiagramDir(1L, record);
            }
            return dirId;
        }
        return 0L;
    }

    @Override
    public Long addSysDir(SysDirVO sysDirVO) {
        MessageUtil.checkEmpty(sysDirVO.getCiCode(), "ciCode");
        /*CCcCi cdt = new CCcCi();
        cdt.setCiCode(sysDirVO.getCiCode());
        List<CcCiInfo> result = ciSwitchSvc.queryCiInfoList(SysUtil.getCurrentUserInfo().getDomainId(), cdt, null, false, true, sysDirVO.getLibType());
        if (result == null || result.size() <= 0) {
            return null;
        }
        CcCiInfo ciInfo = result.get(0);*/

        SysUser loginUser = SysUtil.getCurrentUserInfo();
        Long dirId = null;

        // 新增数据库代码
        VcDiagramDir record = new VcDiagramDir();
        record.setDirName(sysDirVO.getCiName());
        record.setParentId(sysDirVO.getParentId());
        record.setUserId(loginUser.getId());
        record.setDomainId(1L);
        record.setDirType(sysDirVO.getDirType());
        record.setSubjectId(0L);
        record.setDataStatus(1);
        record.setEsSysId(sysDirVO.getCiCode());
        record.setDirInit(0);
        record.setSysDir(1);

        // 系统分类  暂时先不需要的字段
        //record.setSysType(ciInfo.getAttrs().get("子系统分类"));
        //dirId = diagramSvc.saveOrUpdateDiagramDir(1L, record);
        dirId = diagramSvc.saveOrUpdateSysDiagramDir(1L, record,sysDirVO.getLibType());
        return dirId;
    }

    @Override
    public CiGroupPage findDesignCiSysList() {
        //String appName = Env.APP_SUBSYSTEM.getClassName();
        String appName = "DTEA.AA.子系统";
        CCcCiClass cCcCiClass = new CCcCiClass();
        cCcCiClass.setClassNameEqual(appName);
        List<CcCiClassInfo> ccCiClassList = iciClassApiSvc.queryClassByCdt(cCcCiClass);
        if (!CollectionUtils.isEmpty(ccCiClassList)) {
            Long classId = ccCiClassList.get(0).getCiClass().getId();
            ESCISearchBean bean = new ESCISearchBean();
            CCcCi cdt = new CCcCi();
            cdt.setClassId(classId);
            bean.setCdt(cdt);
            Long count = iamsCiDesignSvc.countByQuery(bean);
            bean.setPageSize(count.intValue());
            return iamsCiDesignSvc.queryPageBySearchBean(bean, false);
        }
        return null;
    }

    @Override
    public VcDiagram updateDiagramBaseInfo(VcDiagram record) {
        MessageUtil.checkEmpty(record, "record");
        MessageUtil.checkEmpty(record.getId(), "id");
        return diagramSvc.updateDiagramBaseInfo(record);
    }

    @Override
    public List<VcDiagramInfo> queryDiagramInfoByIds(Long[] ids) {
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        if (ids == null || ids.length == 0) {
            return new ArrayList<>();
        }
        DiagramQ[] diagramQs = new DiagramQ[]{DiagramQ.GROUPS, DiagramQ.TAGS, DiagramQ.CREATOR};
        CVcDiagram cdt = new CVcDiagram();
        cdt.setDomainId(domainId);
        cdt.setIds(ids);
        List<VcDiagramInfo> diagramInfos = diagramSvc.queryDiagramInfoList(domainId, cdt, null, diagramQs);
        trimDiagramList(diagramInfos);
        // 组合视图的缩略图重组
        fillCombs(diagramInfos, false);
        return diagramInfos;
    }

    private Map<String, Object> buildDirMap(Map<String, ESCIInfo> ciCodeAndCiInfoMap, int fieldCount,
                                            VcDiagramDir dir) {
        Map<String, Object> dirMap = MapUtil.newHashMap(fieldCount + 1);
        String classId = "";
        if (checkIsSysDir(dir)) {
            ESCIInfo ciInfo = ciCodeAndCiInfoMap.get(dir.getEsSysId());
            if (ciInfo != null) {
                classId = Objects.toString(ciInfo.getClassId(), "");
            }
        }
        dirMap.put("classId", classId);
        BeanUtil.copyProperties(dir, dirMap);
        return dirMap;
    }

    private boolean checkIsSysDir(VcDiagramDir dir) {
        Integer sysDir = dir.getSysDir();
        return sysDir != null && (sysDir == 1 || sysDir == 3);
    }

    private Map<String, ESCIInfo> ciCodeAndCiInfoMap(List<VcDiagramDir> dirList) {

        List<VcDiagramDir> hasCiCodeDirList = dirList.stream().filter(this::checkIsSysDir).collect(Collectors.toList());
        if (BinaryUtils.isEmpty(hasCiCodeDirList)) {
            return Collections.emptyMap();
        }

        Set<String> esSysCiCodeSet =
                hasCiCodeDirList.stream().map(VcDiagramDir::getEsSysId).collect(Collectors.toSet());

        ESCISearchBean bean = new ESCISearchBean();
        bean.setCiCodes(new ArrayList<>(esSysCiCodeSet));
        bean.setPageSize(3000);
        Page<ESCIInfo> ciSearchPage = ciSwitchSvc.searchESCIByBean(bean, LibType.DESIGN);

        if (ciSearchPage.getTotalPages() == 0) {
            return Collections.emptyMap();
        }

        return ciSearchPage.getData().stream().collect(Collectors.toMap(ESCIInfo::getCiCode,
                esCiInfo -> esCiInfo));
    }

    /**
     * 修整视图信息
     *
     * @param diagramInfos
     */
    private void trimDiagramList(List<VcDiagramInfo> diagramInfos) {
        if (CollectionUtils.isNotEmpty(diagramInfos)) {
            for (VcDiagramInfo vcDiagramInfo : diagramInfos) {
                trimDiagram(vcDiagramInfo);
            }
        }
    }

    /**
     * 重新组装组合视图,始终显示组合视图下第一张视图的缩略图等信息,根据需要填充组合视图下单图的详细信息
     *
     * @param isDetail 是否查询组合视图的详细信息
     */
    private void fillCombs(List<VcDiagramInfo> diagramInfos, boolean isDetail) {
        if (diagramInfos == null || diagramInfos.size() == 0) {
            diagramInfos = new ArrayList<>();
        }
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        // 获取所有的组合视图信息
        List<DcCombDiagram> combDiagrams = new ArrayList<DcCombDiagram>();
        for (VcDiagramInfo info : diagramInfos) {
            VcDiagram vd = info.getDiagram();
            if (BinaryUtils.isEmpty(vd)) {
                continue;
            }
            Integer type = vd.getDiagramType();
            if (type == 2) {
                List<DcCombDiagram> coms = info.getCombDiagrams();
                if (coms != null && coms.size() > 0) {
                    combDiagrams.addAll(coms);
                }
            }
        }
        Map<Long, List<DcCombDiagram>> combMap = BinaryUtils.toObjectGroupMap(combDiagrams, "diagramId");
        Set<Long> combDids = combMap.keySet();
        // 根据组合视图ID查询正常的视图(不在回收站，未被删除)
        Map<Long, VcDiagramInfo> vdMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(combDids)) {
            CVcDiagram vcdt = new CVcDiagram();
            vcdt.setDomainId(domainId);
            vcdt.setStatus(1);
            vcdt.setDataStatus(1);
            vcdt.setIds(combDids.toArray(new Long[0]));
            List<VcDiagramInfo> vdls = diagramSvc.queryDiagramInfoList(domainId, vcdt, "MODIFY_TIME DESC", null);
            if (vdls != null && vdls.size() > 0) {
                for (VcDiagramInfo vcd : vdls) {
                    Long vdid = vcd.getDiagram().getId();
                    vdMap.put(vdid, vcd);
                }
            }
        }
        // 组装数据
        for (VcDiagramInfo dinfo : diagramInfos) {
            // 修整用户头像信息
            if (dinfo == null || dinfo.getDiagram() == null) {
                continue;
            }
            VcDiagram diagram = dinfo.getDiagram();
            Integer diagramType = diagram.getDiagramType();

            if (!BinaryUtils.isEmpty(diagramType) && diagramType == 2) {
                // 先获取组合视图关联信息
                List<DcCombDiagram> combs = dinfo.getCombDiagrams();
                if (combs != null && combs.size() > 0) {
                    // 检查组合视图是否都正常存在，构建新的组合视图关联信息
                    List<DcCombDiagram> dcds = new ArrayList<>();
                    for (DcCombDiagram dcd : combs) {
                        Long dcdid = dcd.getDiagramId();
                        VcDiagramInfo vd = vdMap.get(dcdid);
                        if (vd != null && vd.getDiagram() != null) {
                            dcds.add(dcd);
                        }
                    }
                    if (dcds.size() > 0) {
                        // 组合视图不为空，始终保持组合视图显示第一张图的缩略图信息
                        Long combDidOne = dcds.get(0).getDiagramId();
                        VcDiagramInfo vdInfoOne = vdMap.get(combDidOne);
                        // 修正视图信息
                        trimDiagram(vdInfoOne);
                        VcDiagram vdOne = vdInfoOne.getDiagram();
                        String dicon1One = vdOne.getIcon1();
                        String dbgOne = vdOne.getDiagramBgImg();
                        String dsvgOne = vdOne.getDiagramSvg();
                        String dxmlOne = vdOne.getDiagramXml();
                        String djsonOne = vdOne.getDiagramJson();
                        String svgOne = vdInfoOne.getSvg();
                        String xmlOne = vdInfoOne.getXml();
                        String jsonOne = vdInfoOne.getJson();
                        if (!BinaryUtils.isEmpty(dicon1One) && !dicon1One.startsWith(httpResouceUrl)) {
                            dicon1One = httpResouceUrl + dicon1One;
                        }
                        if (!BinaryUtils.isEmpty(dsvgOne) && !dsvgOne.startsWith(httpResouceUrl)) {
                            dsvgOne = httpResouceUrl + dsvgOne;
                        }
                        if (!BinaryUtils.isEmpty(dxmlOne) && !dxmlOne.startsWith(httpResouceUrl)) {
                            dxmlOne = httpResouceUrl + dxmlOne;
                        }
                        if (!BinaryUtils.isEmpty(djsonOne) && !djsonOne.startsWith(httpResouceUrl)) {
                            djsonOne = httpResouceUrl + djsonOne;
                        }
                        if (!BinaryUtils.isEmpty(dbgOne) && !dbgOne.startsWith(httpResouceUrl)) {
                            dbgOne = httpResouceUrl + dbgOne;
                        }
                        diagram.setIcon1(dicon1One);
                        diagram.setDiagramSvg(dsvgOne);
                        diagram.setDiagramXml(dxmlOne);
                        diagram.setDiagramJson(djsonOne);
                        diagram.setDiagramBgImg(dbgOne);
                        if (!BinaryUtils.isEmpty(svgOne)) {
                            dinfo.setSvg(svgOne);
                        }
                        if (!BinaryUtils.isEmpty(xmlOne)) {
                            dinfo.setXml(xmlOne);
                        }
                        if (!BinaryUtils.isEmpty(jsonOne)) {
                            dinfo.setJson(jsonOne);
                        }
                    } else {
                        // 组合视图为空,清空缩略图
                        dinfo.setSvg(null);
                        dinfo.setXml(null);
                        dinfo.setJson(null);
                        diagram.setDiagramSvg(null);
                        diagram.setIcon1(null);
                        diagram.setDiagramXml(null);
                        diagram.setDiagramBgImg(null);
                        diagram.setDiagramJson(null);
                    }

                    if (dcds.size() > 0) {
                        dinfo.setCombDiagrams(dcds);

                        // 查看视图详情会需要组合视图下单图的详细信息
                        if (isDetail) {
                            List<VcDiagramInfo> combDiagramInfos = new ArrayList<VcDiagramInfo>();
                            for (DcCombDiagram comb : dcds) {
                                Long cdid = comb.getDiagramId();
                                VcDiagramInfo vdInfo = vdMap.get(cdid);
                                trimDiagram(vdInfo);
                                if (!BinaryUtils.isEmpty(vdInfo)) {
                                    combDiagramInfos.add(vdInfo);
                                }
                            }
                            if (combDiagramInfos.size() > 0) {
                                dinfo.setCombDiagramInfos(combDiagramInfos);
                            }
                        }
                    }
                } else {
                    // 组合视图为空,清空缩略图
                    dinfo.setSvg(null);
                    dinfo.setXml(null);
                    diagram.setDiagramSvg(null);
                    diagram.setIcon1(null);
                    diagram.setDiagramXml(null);
                    diagram.setDiagramJson(null);
                    diagram.setDiagramBgImg(null);
                    diagram.setDiagramBgCss(null);
                    diagram.setCi3dPoint(null);
                }
            }

        }
    }

    /**
     * 修整视图信息
     *
     * @param diagramInfo
     */
    private void trimDiagram(VcDiagramInfo diagramInfo) {
        if (diagramInfo != null) {
            fillRsmResource(diagramInfo);
            fillPath(diagramInfo);
            subCreatorAndModifier(diagramInfo);
        }
    }

    /**
     * 填充视图的远程资源信息
     *
     * @param diagramInfo
     */
    private void fillRsmResource(VcDiagramInfo diagramInfo) {
        if (diagramInfo == null) {
            return;
        }
        VcDiagram diagram = diagramInfo.getDiagram();
        if (diagram == null) {
            return;
        }
        String diagramJsonPath = diagram.getDiagramJson();
        if (diagramJsonPath != null && diagramJsonPath.startsWith(httpResouceUrl)) {
            diagramJsonPath = diagramJsonPath.substring(httpResouceUrl.length());
        }
        if (diagramJsonPath != null) {
            try {
                String json = this.getResourceContent(diagramJsonPath);
                diagramInfo.setJson(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void fillPath(VcDiagramInfo diagramInfo) {
        if (diagramInfo == null || diagramInfo.getDiagram() == null) {
            return;
        }
        VcDiagram diagram = diagramInfo.getDiagram();
        // 缩略图
        String icon1 = diagram.getIcon1();
        if (icon1 != null && !icon1.startsWith(httpResouceUrl)) {
            icon1 = httpResouceUrl + icon1;
            diagram.setIcon1(icon1);
        }
        String diagramBgImg = diagram.getDiagramBgImg();
        if (diagramBgImg != null && !BinaryUtils.isEmpty(diagramBgImg.trim())
                && !diagramBgImg.startsWith(httpResouceUrl)) {
            diagramBgImg = httpResouceUrl + diagramBgImg;
            diagram.setDiagramBgImg(diagramBgImg);
        }
        List<VcGroup> groups = diagramInfo.getGroups();
        if (!BinaryUtils.isEmpty(groups)) {
            for (VcGroup vcGroup : groups) {
                String groupImage = vcGroup.getGroupImage();
                if (!BinaryUtils.isEmpty(groupImage) && !groupImage.startsWith(httpResouceUrl)) {
                    groupImage = httpResouceUrl + groupImage;
                }
                vcGroup.setGroupImage(groupImage);
                if (vcGroup.getModifier() != null) {
                    vcGroup.setModifier(subName(vcGroup.getModifier()));
                    vcGroup.setCreator(subName(vcGroup.getCreator()));
                }
            }
        }
        // 修整用户头像信息
        SysUser creator = diagramInfo.getCreator();
        if (creator != null) {
            String icon = creator.getIcon();
            // 这儿判断是因为当前用户是同一个对象，所以再修改会无限拼接，勿删！！！！！！
            if (icon != null && !icon.startsWith(this.httpResouceUrl)) {
                creator.setIcon(httpResouceUrl + icon);
            }
        }
    }

    /**
     * 将创建者和修改者名字剪切掉 aa[bb] --> aa
     *
     * @param diagramInfo 视图信息
     */
    private void subCreatorAndModifier(VcDiagramInfo diagramInfo) {
        if (diagramInfo != null) {
            VcDiagram diagram = diagramInfo.getDiagram();
            if (diagram != null) {
                diagram.setCreator(subName(diagram.getCreator()));
                diagram.setModifier(subName(diagram.getModifier()));
            }
        }
    }

    private String subName(String name) {
        if (name != null) {
            int lastIndexOf = name.lastIndexOf("[");
            if (lastIndexOf > 0) {
                return name.substring(0, lastIndexOf);
            }
        }
        return name;
    }

    private String subRsmSlaveRoot(String url) {
        if (!BinaryUtils.isEmpty(url) && url.startsWith(httpResouceUrl)) {
            return url.substring(httpResouceUrl.length());
        }
        return url;
    }

    /**
     * 将字符串保存/更新 为文件，自动加上日期前缀
     *
     * @param filePath    文件名或文件相对路径
     * @param fileContent 文件内容
     * @return 文件名或文件相对路径
     * @throws IOException
     */
    private String saveOrUpdateResource(String filePath, byte[] fileContent, boolean create) throws IOException {
        if (create) {
            filePath = Paths.get("/" + LocalDate.now(), filePath).toString();
        }

        FileUtil.writeFile(filePath, fileContent);
        return filePath;
    }

    /**
     * 保存或更新格式为base64的png文件
     *
     * @param filePath
     * @param fileContent
     * @param create
     * @return
     */
    private String saveOrUpdatePng(String filePath, String fileContent, boolean create) throws IOException {
        byte[] bs;
        if (fileContent.length() >= fileContent.indexOf(";base64,") + 8) {
            String substring = fileContent.substring(fileContent.indexOf(";base64,") + 8);
            bs = Base64.decodeBase64(substring);

            filePath = this.saveOrUpdateResource(filePath, bs, create);

        }
        return filePath;
    }

    public String getResourceContent(String fileUrl) throws IOException {
        rsmUtils.downloadRsmAndUpdateLocalRsm(fileUrl);
        return FileUtils.readFileToString(new File(localPath, fileUrl));
    }

    private Boolean userIsAdmin(String loginCode) {
        CSysUser cSysUser = new CSysUser();
        cSysUser.setLoginCodeEqual(loginCode);
        List<UserInfo> userInfoByCdt = userApiSvc.getUserInfoByCdt(cSysUser, Boolean.TRUE);
        boolean flag = false;
        for (UserInfo userInfo : userInfoByCdt) {
            for (SysRole role : userInfo.getRoles()) {
                if ("admin".equals(role.getRoleName())) {
                    flag = Boolean.TRUE;
                }
            }
        }
        return flag;
    }

    private void chenkPermission(String loginCode, List<EamDiagramDir> diagramDirList) {
//        List<Long> dirIds = diagramDirList.stream().map(EamDiagramDir::getId).collect(Collectors.toList());
//        List<FolderPermissionManager> folderPermissionManagers = folderPermissionManagerService
//                .getFolderPermissionsByLoginCodeAndDirId(loginCode, dirIds);
        CSysUser cSysUser = new CSysUser();
        cSysUser.setLoginCode(loginCode);
        List<UserInfo> userInfoByCdt = userApiSvc.getUserInfoByCdt(cSysUser, Boolean.TRUE);
        Set<Long> roleIds = Sets.newHashSet();
        for (UserInfo userInfo : userInfoByCdt) {
            Set<SysRole> roles = userInfo.getRoles();
            for (SysRole role : roles) {
                roleIds.add(role.getId());
            }
        }
        List<FolderPermissionManager> folderPermissionByRoleIds = folderPermissionManagerService.getFolderPermissionByRoleIds(roleIds);
        Map<Long, FolderPermissionManager> folderPermissionManagerMap = Maps.newHashMap();
        for (FolderPermissionManager folderPermissionByRoleId : folderPermissionByRoleIds) {
            FolderPermissionManager folderPermissionManager = folderPermissionManagerMap.get(folderPermissionByRoleId.getDirId());
            if (folderPermissionManager != null) {
                mergePermissions(folderPermissionManager,folderPermissionByRoleId);
            }else{
                folderPermissionManagerMap.put(folderPermissionByRoleId.getDirId(),folderPermissionByRoleId);
            }
        }
        Iterator<EamDiagramDir> iterator = diagramDirList.iterator();
        while (iterator.hasNext()) {
            EamDiagramDir next = iterator.next();
            if (!folderPermissionManagerMap.containsKey(next.getId())) {
                iterator.remove();
            } else {
                next.setFolderPermissionManager(folderPermissionManagerMap.get(next.getId()));
            }
        }
    }

    private void mergePermissions(FolderPermissionManager folderPermissionManager,FolderPermissionManager folderPermissionManager2) {
        if (folderPermissionManager.getFolderApplicationScope().getCurrentFolder() || folderPermissionManager2.getFolderApplicationScope().getCurrentFolder()) {
            folderPermissionManager.getFolderApplicationScope().setCurrentFolder(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderApplicationScope().getChildFolder() || folderPermissionManager2.getFolderApplicationScope().getChildFolder()) {
            folderPermissionManager.getFolderApplicationScope().setChildFolder(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderApplicationScope().getChildFolderAndFile() || folderPermissionManager2.getFolderApplicationScope().getChildFolderAndFile()) {
            folderPermissionManager.getFolderApplicationScope().setChildFolderAndFile(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderPermissions().getCreate() || folderPermissionManager2.getFolderPermissions().getCreate()) {
            folderPermissionManager.getFolderPermissions().setCreate(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderPermissions().getDelete() || folderPermissionManager2.getFolderPermissions().getDelete()) {
            folderPermissionManager.getFolderPermissions().setDelete(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderPermissions().getMove() || folderPermissionManager2.getFolderPermissions().getMove()) {
            folderPermissionManager.getFolderPermissions().setMove(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderPermissions().getRead() || folderPermissionManager2.getFolderPermissions().getRead()) {
            folderPermissionManager.getFolderPermissions().setRead(Boolean.TRUE);
        }
        if (folderPermissionManager.getFolderPermissions().getRename() || folderPermissionManager2.getFolderPermissions().getRename()) {
            folderPermissionManager.getFolderPermissions().setRename(Boolean.TRUE);
        }
        if (folderPermissionManager.getFilePermissions().getRead() || folderPermissionManager2.getFilePermissions().getRead()) {
            folderPermissionManager.getFilePermissions().setRead(Boolean.TRUE);
        }
        if (folderPermissionManager.getFilePermissions().getDelete() || folderPermissionManager2.getFilePermissions().getDelete()) {
            folderPermissionManager.getFilePermissions().setDelete(Boolean.TRUE);
        }
        if (folderPermissionManager.getFilePermissions().getMove() || folderPermissionManager2.getFilePermissions().getMove()) {
            folderPermissionManager.getFilePermissions().setMove(Boolean.TRUE);
        }
    }

    private void setAdminPermission(List<EamDiagramDir> diagramDirList) {
        FolderPermissionManager folderPermissionManagerPrototype = new FolderPermissionManager();
        FolderApplicationScope folderApplicationScope = new FolderApplicationScope();
        folderApplicationScope.setChildFolder(Boolean.TRUE);
        folderApplicationScope.setCurrentFolder(Boolean.TRUE);
        folderApplicationScope.setChildFolderAndFile(Boolean.TRUE);
        folderPermissionManagerPrototype.setFolderApplicationScope(folderApplicationScope);
        FolderPermission folderPermission = new FolderPermission();
        folderPermission.setRead(Boolean.TRUE);
        folderPermission.setCreate(Boolean.TRUE);
        folderPermission.setRename(Boolean.TRUE);
        folderPermission.setMove(Boolean.TRUE);
        folderPermission.setDelete(Boolean.TRUE);
        folderPermissionManagerPrototype.setFolderPermissions(folderPermission);
        FilePermission filePermission = new FilePermission();
        filePermission.setRead(Boolean.TRUE);
        filePermission.setMove(Boolean.TRUE);
        filePermission.setDelete(Boolean.TRUE);
        folderPermissionManagerPrototype.setFilePermissions(filePermission);
        for (EamDiagramDir eamDiagramDir : diagramDirList) {
            FolderPermissionManager clone = null;
            try {
                clone = (FolderPermissionManager) folderPermissionManagerPrototype.clone();
            } catch (CloneNotSupportedException e) {
                log.error("权限复制异常", e);
            }
            if (clone == null) {
                clone = new FolderPermissionManager();
            }
            clone.setRoleId(1L);
            clone.setRoleName("admin");
            clone.setDirId(eamDiagramDir.getId());
            eamDiagramDir.setFolderPermissionManager(clone);
        }
    }
}
